package com.travelsky.app.util.system;

import java.util.Hashtable;

import javax.servlet.http.HttpSession;
 
public class LoginUtil {
	private static LoginUtil instance;

	private Hashtable table;

	private LoginUtil() {
		table = new Hashtable();
	}

	public static LoginUtil getInstance() {
		if (null != instance)
			return instance;
		instance = new LoginUtil();
		return instance;
	}

	protected Hashtable getHashTable() {
		return table;
	}

	public void put(Integer accountId, HttpSession session) {
		table.put(accountId, session);
	}

	public void remove(Integer accountId) {
		table.remove(accountId);
	}

	public boolean isLogin(Integer accountId) {
		if (table.get(accountId) != null)
			return true;
		else
			return false;
	}

	public HttpSession getSession(Integer accountId) {
		return (HttpSession) table.get(accountId);
	}

	public void kickOut(Integer accountId, HttpSession newSsssion) {
		HttpSession oldSession = getSession(accountId);

		//login system on the same computer in session validate time
		//so,we cannot invalidate the session COZ the session is same
		if (oldSession != null) {
			try {
				//login twice on the same computer
				if (newSsssion.getId().equals(oldSession.getId()))
					return;
				else
				//login twice on different computer
					oldSession.invalidate(); 
			} catch (Exception e) {
				//the old session is already invalidated! 
			}
		}

		remove(accountId);
		put(accountId, newSsssion);
	}
}
